/*
 * @Author: zjj 
 * @Date: 2018-01-07 02:00:49 
 * @Last Modified by: zjj
 * @Last Modified time: 2018-01-29 19:49:53
 */
import wepy from 'wepy'

/**
 * 登陆封装
 * @param {*} cb(code)
 */
const $login = (cb) => new Promise((resolve, reject) => {
  //登陆
  wepy.login({
    //登陆成功处理,返回code
    success(res) {
      res.code && resolve(res.code)
    },
    fail(err) {
      //登陆失败处理
      console.log(err)
    },
    complete() {
      
    }
  })
}) 

/**
 * 获取用户信息封装，withCredentials为true时需要先调用登陆方法
 * @param {*} withCredentials 
 */
const $getUserInfo = (withCredentials = true) => new Promise((resolve, reject) => {
  wepy.getUserInfo({
    withCredentials,
    lang: 'zh_CN',
    success(res) {
      res.userInfo && resolve(res)
    },
    fail(err) {
      //提示用户授权
      wepy.openSetting && wepy.showModal({
        title: '授权提示',
        content: '希望获得以下权限: \r获取您的公开信息（昵称、头像等）',
        confirmText: '去授权',
        cancelText: '先不授权',
        success: (res) => {
          if (res.confirm) {
            //点击去授权，打开授授权页面
            wepy.openSetting && wepy.openSetting({
              success({authSetting}) {
                if (authSetting['scope.userInfo']) {
                  // 用户打开设置，重新获取信息
                  $getUserInfo();
                }
              }
            })
          }
        }
      })
    }
  })
})

export {$login, $getUserInfo}